package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.service.CheckGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：shirongrong
 * @date ：Created in 2020/3/23
 * @description ：
 * @version: 1.0
 */
@Service
@Slf4j
public class CheckGroupServiceImpl  implements CheckGroupService {
   @Autowired
    private CheckGroupDao checkGroupDao;

 @Transactional
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkItemIds) {
     log.debug("添加检查组......");
     checkGroupDao.add(checkGroup);
     //遍历选择的检查项列表，逐个添加到关系表
     for(Integer checkItemId:checkItemIds){
       Map oneMap=new HashMap<>();
       oneMap.put("checkgroup_id",checkGroup.getId());
       oneMap.put("checkitem_id",checkItemId);
       checkGroupDao.addCheckGroupAndCheckItem(oneMap);
     }
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> pageList=checkGroupDao.selectByConditing(queryString);
        return new PageResult(pageList.getTotal(),pageList.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
     log.debug(">>>findById:{}",id);
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }
    @Transactional
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        // 保存检查组信息
        checkGroupDao.edit(checkGroup);
        // 删除检查组之前关联关系
        checkGroupDao.deleteCheckItemsListByCheckGroupId(checkGroup.getId());
        // 保存新的关系
        for (Integer checkItemId :checkitemIds) {
            Map maps = new HashMap();
            maps.put("checkgroup_id",checkGroup.getId());
            maps.put("checkitem_id",checkItemId);
            checkGroupDao.addCheckGroupAndCheckItem(maps);
        }
    }

}
